﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using SD.BUS;
using SD.IBUS;
using SD.Entities;
using SD.Common;
using System.Collections.Generic;
using System.Data.SqlClient;

namespace SD.UI
{
    public partial class UpdateDirectorate : BasePage
    {
        //Type Sort Girdview
        private static string ASCENDING = " ASC";
        private static string DESCENDING = " DESC";
        IDepartmentBIZ departmentBIZ = new DepartmentBIZ();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Set value for Session
                Session["orgId"] = Request.Params["orgId"];
                if (Request.Params["dirId"] == null)
                {
                    btnInActive.Visible = false;
                    TabDepartment.Visible = false;
                }
                else
                {
                    TabDepartment.Visible = true;
                    LoadData();
                    // set active status
                    IDirectorateBIZ directorateBIZ = new DirectorateBIZ();
                    directorateBIZ.SetActive(Request.Params["dirId"], true);
                    // no filter string param
                    if (Session["dString"] == null)
                    {
                        Session.Add("dString", "");
                    }

                    // no include inactive param
                    if (Session["includeInactiveDirect"] == null)
                    {
                        Session.Add("includeInactiveDirect", false);
                    }
                    else
                    {
                        chkInActive.Checked = Boolean.Parse(Session["includeInactiveDirect"].ToString());
                    }
                    FillData(Session["dString"].ToString(), Convert.ToBoolean(Session["includeInactiveDirect"]), Request.Params["dirId"]);

                }
            }
        }
        #region Detail
        /// <summary>
        /// Active tabcontainer Default
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
        {
            Session["indexTab"] = TabContainer1.ActiveTabIndex;
        }
        /// <summary>
        /// Event Save Directorate
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Request.Params["orgId"] == null)
            {
                Update();
            }
            else
            {
                InsertDirectorate();
            }
        }
        /// <summary>
        /// Insert Directorate
        /// </summary>
        protected void InsertDirectorate()
        {
            // Create IDirectorateBIZ object
            IDirectorateBIZ iDirectorateBIZ = new DirectorateBIZ();
            // Create Directorate object
            Directorate directorate = new Directorate();

            // Detail 1
            directorate.Name = tbxDirectorateName.Text;

            // Create the list of Directorate
            List<Directorate> listDirectorate = new List<Directorate>();

            // Check the duplication of Directorate name
            listDirectorate = iDirectorateBIZ.GetDirByName(directorate.Name.ToString().Trim());

            // Check Organization name has existed in database
            if (listDirectorate.Count > 0)
            {
                ShowMessage("Directorate name has existed in system. Please input another name.");

                // Load values to enable textbox
                tbxAddressLine1.Text = hdfLine1.Value;
                tbxAddressLine2.Text = hdfLine2.Value;
                tbxAddressLine3.Text = hdfLine3.Value;
                tbxPostcode.Text = hdfPostCode.Value;
                tbxCityTown.Text = hdfTown.Value;
                tbxCounty.Text = hdfCountry.Value;
                tbxNationCountry.Text = hdfCountry.Value;
                tbxTypeOfBussiness.Text = hdfBussiness.Value;
                tbxSICCode.Text = hdfSicCode.Value;
                tbxLeadContact.Text = hdfContactName.Value;
            }
            else
            {

                directorate.ShortDescription = tbxDirShortDes.Text;
                directorate.FullDescription = tbxDirFullDescription.Text;
                directorate.Phone = tbxPhoneNumber.Text;
                directorate.Fax = tbxFax.Text;
                directorate.Email = tbxEmail.Text;
                directorate.Web = tbxWebAddress.Text;
                directorate.Charity = tbxCharityNumber.Text;
                directorate.Company = tbxCompanyNumber.Text;

                // Create Address object
                Address address = new Address();
                // Bind value to object
                address.AddressId = txtAddressID.Value;
                directorate.Address = address;

                // Create ReferenceData object
                ReferenceData referenceData = new ReferenceData();
                // Bind value to object
                referenceData.RefId = txtBussinessID.Value;
                directorate.BusinessType = referenceData;

                // Create Contact object
                Contact contact = new Contact();
                // Bind value to object
                contact.ContactId = txtContactID.Value;
                directorate.Contact = contact;
                //create Organization object
                Organization organization = new Organization();
                //Bind value to object
                string orgId = Request.QueryString["orgId"];
                organization.OrgId = orgId;
                directorate.Organization = organization;
                directorate.IsActive = true;
                // Insert new Directorate
                iDirectorateBIZ.Insert(directorate);

                // If insert successful
                ShowMessageAndRedirect(INFO_INSERT_SUCCESSFUL, "EditOrganization.aspx?orgId=" + Request.Params["orgId"]);
            }
        }
        /// <summary>
        /// Handle event checked of ckbCoppyAddress
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ckbCoppyAddress_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbCoppyAddress.Checked)
            {
                linkPostcode.Visible = false;
                CoppyAddress();
            }
            else
            {
                linkPostcode.Visible = true;
                tbxAddressLine1.Text = "";
                tbxAddressLine2.Text = "";
                tbxAddressLine3.Text = "";

                tbxCityTown.Text = "";
                tbxCounty.Text = "";
                tbxNationCountry.Text = "";
                tbxPostcode.Text = "";

            }
        }
        /// <summary>
        /// Coppy Address from EditOrganization Page.
        /// </summary>
        protected void CoppyAddress()
        {
            IOrganizationBIZ iOrganizationBIZ = new OrganizationBIZ();
            Organization organization = null;

            organization = iOrganizationBIZ.GetById(Session["orgId"].ToString());

            if (organization == null) // error occur
            {
                return;
            }

            if (organization.Address != null) // set address if it is not null
            {
                // set address details
                tbxAddressLine1.Text = organization.Address.Line1;
                tbxAddressLine2.Text = organization.Address.Line2;
                tbxAddressLine3.Text = organization.Address.Line3;

                tbxCityTown.Text = organization.Address.Town == null ? "" : organization.Address.Town.Name;
                tbxCounty.Text = organization.Address.County == null ? "" : organization.Address.County.Name;
                tbxNationCountry.Text = organization.Address.Country == null ? "" : organization.Address.Country.Name;
                tbxPostcode.Text = organization.Address.PostCode;

                //set hidden field
                txtAddressID.Value = organization.Address.AddressId;
            }
        }
        /// <summary>
        /// Return to EditOrganization Page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("EditOrganization.aspx?orgId=" + Session["orgId"]);
        }
        /// <summary>
        /// Set inActive a Directorate
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnInActive_Click(object sender, EventArgs e)
        {
            IDirectorateBIZ iDirectorateBIZ = new DirectorateBIZ();

            iDirectorateBIZ.SetActive(Request.QueryString["dirId"].ToString(), false);
            ShowMessageAndRedirect(INFO_SAVE_SUCCESSFUL, "EditOrganization.aspx?orgId=" + Session["orgId"]);
        }
        /// <summary>
        /// Amend Directorate Update
        /// </summary>
        private void Update()
        {
            IDirectorateBIZ iDirectorateBIZ = new DirectorateBIZ();

            // Check Directorate name has existed in database
            if (IsDuplicateName(tbxDirectorateName.Text.Trim()))
            {
                ShowMessage(ERROR_DUPLICATE_NAME);

                // Load values from hidden field
                tbxAddressLine1.Text = hdfLine1.Value;
                tbxAddressLine2.Text = hdfLine2.Value;
                tbxAddressLine3.Text = hdfLine3.Value;
                tbxPostcode.Text = hdfPostCode.Value;
                tbxCityTown.Text = hdfTown.Value;
                tbxCounty.Text = hdfCountry.Value;
                tbxNationCountry.Text = hdfCountry.Value;
                tbxTypeOfBussiness.Text = hdfBussiness.Value;
                tbxSICCode.Text = hdfSicCode.Value;
                tbxLeadContact.Text = hdfContactName.Value;
            }
            else
            {
                Directorate dir = new Directorate();
                // Set Detail 1
                dir.DirectorateId = Request.QueryString["dirId"].ToString();
                dir.Name = tbxDirectorateName.Text;
                dir.ShortDescription = tbxDirShortDes.Text;
                dir.FullDescription = tbxDirFullDescription.Text;
                dir.Phone = tbxPhoneNumber.Text;
                dir.Fax = tbxFax.Text;
                dir.Email = tbxEmail.Text;
                dir.Web = tbxWebAddress.Text;
                dir.Charity = tbxCharityNumber.Text;
                dir.Company = tbxCompanyNumber.Text;

                Address address = new Address();
                address.AddressId = String.IsNullOrEmpty(txtAddressID.Value) ? null : txtAddressID.Value;
                dir.Address = address;

                ReferenceData referenceData = new ReferenceData();
                referenceData.RefId = String.IsNullOrEmpty(txtBussinessID.Value) ? null : txtBussinessID.Value;
                dir.BusinessType = referenceData;

                Contact contact = new Contact();
                contact.ContactId = String.IsNullOrEmpty(txtContactID.Value) ? null : txtContactID.Value;
                dir.Contact = contact;

                dir.IsActive = true;

                // Update to database
                iDirectorateBIZ.Update(dir);
                ShowMessageAndRedirect(INFO_SAVE_SUCCESSFUL, "EditOrganization.aspx?orgId=" + Session["orgId"]);
            }
        }
        /// <summary>
        /// Check Duplicate Name of Directorate
        /// </summary>
        /// <param name="dirName"></param>
        /// <returns></returns>
        private Boolean IsDuplicateName(String dirName)
        {
            IDirectorateBIZ iDirectorateBIZ = new DirectorateBIZ();
            List<Directorate> lstDir = new List<Directorate>();

            lstDir = iDirectorateBIZ.GetDirByName(tbxDirectorateName.Text.Trim());

            if ((lstDir.Count > 0))
            {
                if (lstDir[0].DirectorateId.Equals(Request.Params["dirId"]))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// Fill Data from EditOrganization Page into UpdateOrganization Page
        /// </summary>
        protected void LoadData()
        {
            IDirectorateBIZ iDirectorateBIZ = new DirectorateBIZ();
            Directorate directorate = null;

            directorate = iDirectorateBIZ.GetById(Request.Params["dirId"]);

            if (directorate == null) // error occur
            {
                return;
            }

            // Set value for detail 1 tab
            tbxDirectorateName.Text = directorate.Name;

            tbxDirShortDes.Text = directorate.ShortDescription;

            tbxLeadContact.Text = directorate.Contact == null ? "N/A" : directorate.Contact.Surname;

            if (directorate.Address != null) // set address if it is not null
            {
                // set address details
                tbxAddressLine1.Text = directorate.Address.Line1;
                tbxAddressLine2.Text = directorate.Address.Line2;
                tbxAddressLine3.Text = directorate.Address.Line3;

                tbxCityTown.Text = directorate.Address.Town == null ? "" : directorate.Address.Town.Name;
                tbxCounty.Text = directorate.Address.County == null ? "" : directorate.Address.County.Name;
                tbxNationCountry.Text = directorate.Address.Country == null ? "" : directorate.Address.Country.Name;
                tbxPostcode.Text = directorate.Address.PostCode;
            }

            tbxDirFullDescription.Text = directorate.FullDescription;

            tbxSICCode.Text = directorate.BusinessType == null ? "N/A" : directorate.BusinessType.RefCode;

            tbxTypeOfBussiness.Text = directorate.BusinessType == null ? "N/A" : directorate.BusinessType.RefValue;

            //tbxOrgShortDes.Text = directorate.ShortDescription;

            tbxPhoneNumber.Text = directorate.Phone;

            tbxWebAddress.Text = directorate.Web;

            tbxFax.Text = directorate.Fax;

            tbxEmail.Text = directorate.Email;

            tbxCharityNumber.Text = directorate.Charity;

            tbxCompanyNumber.Text = directorate.Company;
            // set hidden field
            txtAddressID.Value = directorate.Address == null ? null : directorate.Address.AddressId;
            txtBussinessID.Value = directorate.BusinessType == null ? null : directorate.BusinessType.RefId;
            txtContactID.Value = directorate.Contact == null ? null : directorate.Contact.ContactId;
            hdfLine1.Value = tbxAddressLine1.Text;
            hdfLine2.Value = tbxAddressLine2.Text;
            hdfLine3.Value = tbxAddressLine3.Text;
            hdfPostCode.Value = tbxPostcode.Text;
            hdfTown.Value = tbxCityTown.Text;
            hdfCountry.Value = tbxCounty.Text;
            hdfCountry.Value = tbxNationCountry.Text;
            hdfBussiness.Value = tbxTypeOfBussiness.Text;
            hdfSicCode.Value = tbxSICCode.Text;
            hdfContactName.Value = tbxLeadContact.Text;
            //set session for button back
            Session["orgId"] = directorate.Organization.OrgId;
        }
        #endregion
        #region Departments
        public void FillData(String filterString, Boolean includeInactive, string dirId)
        {
            if (filterString.Equals("")) // show all organization
            {

                DataTable dt = departmentBIZ.GetAll(includeInactive,dirId);
                BindData(dt);

            }
            else
            {
                DataTable dt = departmentBIZ.GetByFilter(filterString,includeInactive,dirId);
                BindData(dt);

            }
            Session["dString"] = filterString;
        }
        
        private void BindData(DataTable dtbDataSource)
        {
            // If have data in table
            if (dtbDataSource.Rows.Count > 0)
            {
                gvDepartment.DataSource = dtbDataSource;
                gvDepartment.DataBind();
                lblMessage.Text = string.Empty;
            }
            else // if have no data in table
            {
                dtbDataSource.Rows.Add(dtbDataSource.NewRow());
                gvDepartment.DataSource = dtbDataSource;
                gvDepartment.DataBind();
                gvDepartment.Rows[0].Visible = false;
                lblMessage.Text = "No records found";
            }
        }
        private SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                    ViewState["sortDirection"] = SortDirection.Ascending;
                return (SortDirection)ViewState["sortDirection"];
            }
            set { ViewState["sortDirection"] = value; }
        }
        private void SortGridView(string sortExpression, string direction)
        {
            DataTable tb = new DataTable();
            // List all organization
            if (Session["dString"].Equals(""))
            {
                tb =departmentBIZ.GetAll(Convert.ToBoolean(Session["includeInactiveDirect"]), Request.Params["dirId"]);

            }
            // List organization is up to remain filter
            else
            {
                tb = departmentBIZ.GetByFilter(Session["dString"].ToString(), Convert.ToBoolean(Session["includeInactiveDirect"]), Request.Params["dirId"]);
            }
            if (tb.Rows.Count > 0)
            {
                DataView dv = new DataView(tb);
                dv.Sort = sortExpression + direction;
                gvDepartment.DataSource = dv;
                gvDepartment.DataBind();
            }
            else
            {
                tb.Rows.Add(tb.NewRow());
                gvDepartment.DataSource = tb;
                gvDepartment.DataBind();
                gvDepartment.Rows[0].Visible = false;
                lblMessage.Text = "No records found";
            }

        }


        protected void lbnAll_Click(object sender, EventArgs e)
        {
            FillData("", Convert.ToBoolean(Session["includeInactiveDirect"]), Request.Params["dirId"]);
        }
  

        protected void lbn09_Click(object sender, EventArgs e)
        {
            FillData("[0-9]%", Convert.ToBoolean(Session["includeInactiveDirect"].ToString()), Request.Params["dirId"]);
        }

        protected void lbnABCDE_Click(object sender, EventArgs e)
        {
            FillData("[A-E]%", Convert.ToBoolean(Session["includeInactiveDirect"].ToString()), Request.Params["dirId"]);
        }

        protected void lbnFGHIJ_Click(object sender, EventArgs e)
        {
            FillData("[F-J]%", Convert.ToBoolean(Session["includeInactiveDirect"].ToString()), Request.Params["dirId"]);
        }

        protected void lbnKLMN_Click(object sender, EventArgs e)
        {
            FillData("[K-N]%", Convert.ToBoolean(Session["includeInactiveDirect"].ToString()), Request.Params["dirId"]);
        }

        protected void lbnOPQR_Click(object sender, EventArgs e)
        {
            FillData("[O-R]%", Convert.ToBoolean(Session["includeInactiveDirect"].ToString()), Request.Params["dirId"]);
        }

        protected void lbnSTUV_Click(object sender, EventArgs e)
        {
            FillData("[S-V]%", Convert.ToBoolean(Session["includeInactiveDirect"].ToString()), Request.Params["dirId"]);
        }

        protected void lbnWXYZ_Click(object sender, EventArgs e)
        {
            FillData("[W-Z]%", Convert.ToBoolean(Session["includeInactiveDirect"].ToString()), Request.Params["dirId"]);
        }

        protected void chkInActive_CheckedChanged(object sender, EventArgs e)
        {
            Session["includeInactiveDirect"] = chkInActive.Checked;
            FillData(Session["dString"].ToString(), chkInActive.Checked, Request.Params["dirId"]);
        }

        protected void btnCreateDepartment_Click(object sender, EventArgs e)
        {
            Response.Redirect("UpdateDepartment.aspx?dirId="+Request.Params["dirId"]);
        }


        protected void gvDepartment_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvDepartment.PageIndex = e.NewPageIndex;
            FillData(Session["dString"].ToString(), Convert.ToBoolean(Session["includeInactiveDirect"].ToString()), Request.Params["dirId"]);
        }

        protected void gvDepartment_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression;
            ViewState["SortExpression"] = sortExpression;
            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                SortGridView(sortExpression, DESCENDING);
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                SortGridView(sortExpression, ASCENDING);
            }

        }
        #endregion

    }
}
